package main

import (
	_ "GraduationProject/public/tools"
	"strconv"

	"GraduationProject/public/db"
	"GraduationProject/public/elastic_search"
	"GraduationProject/public/params"
	"GraduationProject/public/tools"
	"GraduationProject/rpcsupport"
	"fmt"
)

func init() {
	db.ConnectDB()
	db.RedisConnect()
	db.ElasticSearchConnect()
}

/*
	爬虫存储服务
*/
func main() {
	err := rpcsupport.ServeRpc(tools.Conf.Get("port"), &Storage{})
	if err != nil {
		panic(err)
	}
}

type Storage struct{}

func (s *Storage) Save(result params.Result, message *params.Message) error {
	fmt.Printf("Storage.Save result: %#v\n", result.Result)
	for _, v := range result.Result {
		if err := db.DB.Create(&v).Error; err != nil {
			errElastic := elastic_search.Elastic(db.ElasticClient,
				elastic_search.TypeStorage,
				elastic_search.DefaultLog{
					Level: elastic_search.LevelWarning,
					Log:   elastic_search.Error{Error: err, Body: v},
				})
			if errElastic != nil {
				fmt.Printf("log.Elastic error: %s\t\tdb.DB.Create(v).Error:%s\n", errElastic.Error(), err.Error())
			}
			// 数据库存储失败，直接跳过
			fmt.Printf("db create v error: v %#v\terror: %v\n", v, err)
			continue
		}
		if !v.NotElastic {
			err := elastic_search.SaveRecord(db.ElasticClient,
				"result", strconv.Itoa(int(v.SeedID)), v)
			if err != nil {
				fmt.Printf("elastic_search.SaveRecord error: %s\n", err.Error())
			}
		}
	}

	*message = params.Message{
		Status:  200,
		Message: "success",
	}
	return nil
}
